package com.zjuee.web.ledger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjuee.base.constant.DictionaryConstants;
import com.zjuee.base.dto.common.login.LoginDto;
import com.zjuee.base.enums.DictionaryType;
import com.zjuee.base.enums.RedisCacheType;
import com.zjuee.base.exception.ServiceException;
import com.zjuee.base.utils.DateUtils;
import com.zjuee.core.translation.service.TranslateData;
import com.zjuee.core.utils.ExcelUtil;
import com.zjuee.core.utils.ExportExcel;
import com.zjuee.base.dto.common.ledger.LedgerDisposeGatherDto;
import com.zjuee.base.model.common.ledger.LedgerDisposeBill;
import com.zjuee.base.model.common.ledger.LedgerDisposeGather;
import com.zjuee.service.LedgerDisposeGatherService;
import com.zjuee.vo.LedgerDisposeGatherVo;
import com.zjuee.web.ledger.mapper.LedgerDisposeBillMapper;
import com.zjuee.web.ledger.mapper.LedgerDisposeGatherMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author wu liang
 * @since 1.0
 */
@Slf4j
@Service
public class LedgerDisposeGatherServiceImpl implements LedgerDisposeGatherService {

    @Resource
    private LedgerDisposeGatherMapper ledgerDisposeGatherMapper;
    @Resource
    private LedgerDisposeBillMapper ledgerDisposeBillMapper;
    @Resource
    LoginDto loginDto;
    @Resource
    TranslateData translateData;

    @Override
    @Transactional
    public Long add(LedgerDisposeGather type) {
        String year = String.valueOf(DateUtils.getYear(new Date()));
        QueryWrapper<LedgerDisposeGather> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bci_id", type.getBciId())
                .eq("wldg_code", type.getWldgCode())
                .eq("wldg_dispose_mode", type.getWldgDisposeMode())
                .eq("wldg_dispose_mode", type.getWldgDisposeSmode())
                .eq("wldg_year", year);
        LedgerDisposeGather ledgerDisposeGather = ledgerDisposeGatherMapper.selectOne(queryWrapper);
        if (ledgerDisposeGather != null) {
            throw new ServiceException("本年度该台账已存在，不能重复添加!");
        }
        type.setWldgYear(year);
        type.setWldgCreator(loginDto.getUserName());
        type.setWldgCreateTime(new Date());
        int insert = ledgerDisposeGatherMapper.insert(type);
        return Long.parseLong(String.valueOf(insert));
    }

    @Override
    @Transactional
    public boolean delete(Long id, Long validateId) {
        QueryWrapper<LedgerDisposeBill> queryWrapper = new QueryWrapper<LedgerDisposeBill>().eq("wldg_id", id);
        List<LedgerDisposeBill> billList = ledgerDisposeBillMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(billList)) {
            throw new ServiceException("已产生数据不能删除!");
        }
        LedgerDisposeGather ledgerDisposeGather = ledgerDisposeGatherMapper.selectById(id);
        if (ledgerDisposeGather == null) {
            throw new ServiceException("台账信息不能为空!");
        }
        int deleteById = ledgerDisposeGatherMapper.deleteById(id);
        if (deleteById <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean update(LedgerDisposeGather type) {
        LedgerDisposeGather ledgerDisposeGather = ledgerDisposeGatherMapper.selectById(type.getId());
        if (ledgerDisposeGather == null) {
            throw new ServiceException("台账信息不能为空!");
        }
        int updateById = ledgerDisposeGatherMapper.updateById(type);
        if (updateById <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public LedgerDisposeGather selectById(Long id, Long validateId) {
        LedgerDisposeGather ledgerDisposeGather = ledgerDisposeGatherMapper.selectById(id);
        if (ledgerDisposeGather != null) {
            if (!ledgerDisposeGather.getBciId().equals(validateId)) {
                throw new ServiceException("无权限操作!");
            }
        }
        return ledgerDisposeGather;
    }

    @Override
    public Page<LedgerDisposeGather> list(LedgerDisposeGatherDto dto) {
        dto.setBciId(loginDto.getOrgBusinessId());
        Page<LedgerDisposeGather> disposeGatherPage = ledgerDisposeGatherMapper.selectPageList(dto.getPage().convert(), dto);
        disposeGatherPage.getRecords().stream().forEach(ledgerDisposeGather -> {
            if (ledgerDisposeGather.getWldgModel().equals(DictionaryConstants.MODEL_DANGER)){
                translateData.translateData(ledgerDisposeGather,
                        "LedgerDisposeGatherListHandle",
                        String.valueOf(DictionaryType.PB_WASTE_TYPE.getValue()),
                        String.valueOf(RedisCacheType.DISPOSE_TYPE),
                        String.valueOf(RedisCacheType.DISPOSE_STYPE),
                        String.valueOf(DictionaryType.WL_EDIT_STATUS.getValue()),
                        String.valueOf(DictionaryType.PB_WASTE_MODEL.getValue())
                );
            }else if (ledgerDisposeGather.getWldgModel().equals(DictionaryConstants.MODEL_SOLID)){
                translateData.translateData(ledgerDisposeGather,
                        "LedgerDisposeGatherListHandle",
                        String.valueOf(DictionaryType.PB_WASTE_TYPE.getValue()),
                        String.valueOf(RedisCacheType.SOLID_TYPE),
                        String.valueOf(RedisCacheType.SOLID_STYPE),
                        String.valueOf(DictionaryType.WL_EDIT_STATUS.getValue()),
                        String.valueOf(DictionaryType.PB_WASTE_MODEL.getValue())
                );
            }
        });
        return disposeGatherPage;
    }

    @Override
    public LambdaQueryWrapper<LedgerDisposeGather> fuzzyQuery(LedgerDisposeGatherDto dto) {
        return null;
    }

    @Override
    public List<LedgerDisposeGather> getList(LedgerDisposeGather ledgerDisposeGather) {
        ledgerDisposeGather.setBciId(loginDto.getOrgBusinessId());
        List<LedgerDisposeGather> list = ledgerDisposeGatherMapper.getList(ledgerDisposeGather);
        translateData.translateData(list,
                "LedgerDisposeGatherListHandle",
                String.valueOf(DictionaryType.PB_WASTE_TYPE.getValue()),
                String.valueOf(RedisCacheType.DISPOSE_TYPE),
                String.valueOf(RedisCacheType.DISPOSE_STYPE),
                String.valueOf(DictionaryType.WL_EDIT_STATUS.getValue()),
                String.valueOf(DictionaryType.PB_WASTE_MODEL.getValue())
        );
        return list;
    }

    @Override
    public void exportExcel(LedgerDisposeGather ledgerDisposeGather) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        List<LedgerDisposeGather> list = ledgerDisposeGatherMapper.getList(ledgerDisposeGather);
        if (!CollectionUtils.isEmpty(list)) {
            //翻译数据
            List<Map<String, Object>> dataMap = (List<Map<String, Object>>)  translateData.translateData(list,
                    "LedgerDisposeGatherListHandle",
                    String.valueOf(DictionaryType.PB_WASTE_TYPE.getValue()),
                    String.valueOf(RedisCacheType.DISPOSE_TYPE),
                    String.valueOf(RedisCacheType.DISPOSE_STYPE),
                    String.valueOf(DictionaryType.WL_EDIT_STATUS.getValue()),
                    String.valueOf(DictionaryType.PB_WASTE_MODEL.getValue())
            );
            String[] key = {"id", "wldgModelStr", "wldgTypeStr", "wldgMarkStr", "wldgBcode", "wldgScode",  "wldgYear","wldgDisposeModeStr","wldgDisposeSmodeStr", "wldgTotalShift", "wldgPreStock", "wldgTotalDispose", "wldgStock", "wldgChange", "wldgCreateTime", "wldgModifiedTime"};
            String[] str = {"序号", "废物大类别", "废物小类别", "台账类型", "废物大类", "废物小类",  "年份","处置方式(大类)", "处置方式(小类)","转入量总计(吨)", "上年底库存量(吨)", "处置量总计(吨)",  "当前库存量(吨)", "库存变动量(吨)", "创建时间", "修改时间"};

            List<ExportExcel> exportExcelList = new ArrayList<ExportExcel>();
            ExportExcel e1 = new ExportExcel("处置台账列表", "处置台账列表", key, str, dataMap);
            exportExcelList.add(e1);
            ExcelUtil.download("处置台账列表", exportExcelList, request, response);
        }
    }

    @Override
    public LedgerDisposeGather selectOne(QueryWrapper<LedgerDisposeGather> queryWrapper) {
        return ledgerDisposeGatherMapper.selectOne(queryWrapper);
    }

    @Override
    public List<LedgerDisposeGather> getListMap(LedgerDisposeGatherVo condition) {
        return ledgerDisposeGatherMapper.getListMap(condition);
    }

    @Override
    public void updateBatch(ArrayList<LedgerDisposeGather> updateLedger) {
        ledgerDisposeGatherMapper.updateBatch(updateLedger);
    }

    @Override
    public List<LedgerDisposeGather> insertBatch(ArrayList<LedgerDisposeGather> ledgerDisposeGathersInsert) {
        ledgerDisposeGatherMapper.insertBatch(ledgerDisposeGathersInsert);
        return ledgerDisposeGathersInsert;
    }
}
